//
//  BJTableViewController.m
//  BobNews
//
//  Created by lanou3g on 16/5/7.
//  Copyright © 2016年 YJC. All rights reserved.
//

#import "BJTableViewController.h"
#import "NetWorkRequestManager.h"
#import "BJModel.h"
#import "BJTableViewCell.h"
#import "BJViewController.h"
#import "CycleView.h"
#import "LORefresh.h"
#import "BJImageModelCell.h"
#import "BJMoreModelCell.h"

#import "ToutiaoPhotoViewController.h"


@interface BJTableViewController ()

@property (nonatomic,strong) NSMutableArray *dataSoureArray;

@property (nonatomic,strong) CycleView *cycleView;

@property (nonatomic,strong) LORefresh *headerRefresh;

@property (nonatomic,strong) NSString *start;


@end

@implementation BJTableViewController

-(void)dealloc{
    [self.tableView removeObserver:[self.tableView gifHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    
    self.start = @"0";
    self.dataSoureArray = [NSMutableArray new];
    
    [self loadData];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"BJImageModelCell" bundle:nil] forCellReuseIdentifier:@"BJImageModel"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"BJMoreModelCell" bundle:nil] forCellReuseIdentifier:@"BJMoreModel"];
    
    
    self.cycleView = [[CycleView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200) interVal:3];
    self.tableView.tableHeaderView = self.cycleView;
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderGif refreshingBlock:^{
        
        [weakSelf.dataSoureArray removeAllObjects];
        [weakSelf.tableView reloadData];
        
        [weakSelf loadData];
        
        
        
    }];
    
    self.headerRefresh = [self.tableView gifHeader];
    [self.headerRefresh setGifName:@"pipi.gif"];

    
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        NSInteger count = weakSelf.dataSoureArray.count;
        
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        
        [weakSelf loadData];
        
    }];
    
    
}

-(void)loadData{
    
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:@"http://c.3g.163.com/nc/article/local/5YyX5Lqs/0-20.html"] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            for (NSDictionary *listDict in jsonDict[@"北京"]) {
                BJModel *model = [BJModel modelWithDictionary:listDict];
                
                [self.dataSoureArray addObject:model];

                
            }
            
            NSArray *imgArray = jsonDict[@"北京"];
            NSString *imgStr = imgArray[0][@"imgsrc"];
            NSMutableArray *mArray = [NSMutableArray new];
            [mArray addObject:imgStr];
            
            NSArray *imgexArray = imgArray[0][@"imgextra"];
            for (NSDictionary *imgDict in imgexArray) {
                [mArray addObject:imgDict[@"imgsrc"]];
                
            }
            
            
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                
                [self.tableView reloadData];
                
                self.cycleView.imgNameArray = mArray;
                
                [[self.tableView gifHeader]endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
                
                
            });
            
        }
        
    }];
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSoureArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
  
         BJTableViewCell *cell = [BJTableViewCell initWithTableView:tableView Model:self.dataSoureArray[indexPath.row] IndexPath:indexPath];
        return cell;
      
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *modelName = NSStringFromClass([self.dataSoureArray[indexPath.row] class]);
    
    Class CellClass = NSClassFromString([modelName stringByAppendingString:@"Cell"]);
    
    return [CellClass height];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BJModel *model = self.dataSoureArray[indexPath.row];
    NSString *photo = model.photosetID;
    if (photo) {
        ToutiaoPhotoViewController *photoVC = [[ToutiaoPhotoViewController alloc]init];
        photoVC.photosetID = model.photosetID;
        [self.navigationController pushViewController:photoVC animated:YES];
    } else {
        BJViewController *bjVC = [[BJViewController alloc]init];
        
        bjVC.urlStr = [self.dataSoureArray[indexPath.row] BJUrl];
        
        [self.navigationController pushViewController:bjVC animated:YES];
    }
    
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
